import { getToken, removeToken, setToken } from "@/utils/cache";
import types from "../actionTypes";
import setting from "@/setting";
const state = {
  token: getToken(),
  schoolConfig: {},
  userInfo: {},
  loginType: "",
};

const mutations = {
  [types.SET_TOKEN](state, token) {
    state.token = token;
  },
  [types.SET_SCHOOLCONFIG](state, schoolConfig) {
    state.schoolConfig = schoolConfig;
  },
  [types.SET_USERINFO](state, userInfo) {
    state.userInfo = userInfo;
  },
  [types.SET_LOGINTYPE](state, loginType) {
    state.loginType = loginType;
  },
};

const actions = {
  [types.GET_WXCODE]() {
    // 获取code
    let urlNow = encodeURIComponent(window.location.href);
    let scope = "snsapi_base"; // snsapi_userinfo   //静默授权 用户无感知
    const url2 = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${setting.wxappid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=123#wechat_redirect`;
    window.location.replace(url2);
  },
  // 统一处理登录成功后的数据
  [types.LOGIN_AFTER]({ commit }, result) {
    return new Promise((resolve) => {
      let { schoolConfig, token, data } = result;
      commit(types.SET_USERINFO, data.shift());
      token && commit(types.SET_TOKEN, token);
      token && setToken(token);
      schoolConfig && commit(types.SET_SCHOOLCONFIG, schoolConfig);
      resolve();
    });
  },
  // 退出登录
  [types.LOGOUT]({ commit, state }) {
    commit(types.SET_USERINFO, {});
    commit(types.SET_TOKEN, "");
    commit(types.SET_SCHOOLCONFIG, {});
    removeToken();
    switch (state.loginType) {
      case 4: // 统一身份认证的时候退出登录
        window.location.href = setting.logoutUrl;
        break;
      default:
        break;
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
